<template>
  <div class="ai">
		<template v-if="!unSearch">
			<div class="unsearch">
				<div class="profession">
					<div class="title">
						<div class="one">1</div>
						<div class="two">/5</div>
						<div class="tip">目标专业</div>
					</div>
					<div style="display: flex; align-items: center">
						<el-cascader
							v-if="selectType"
							v-model="search"
							size="large"
							placeholder="选择专业"
							:options="educateTypeOption"
							:props="props"
							@change="professionChange"
						/>
						<el-select
							v-else
							clearable
							filterable
							remote
							size="large"
							:remote-method="remoteMethod"
							@change="selectMajor"
							placeholder="请输入专业名称"
							v-model="search"
							:loading="searchMajorLoading"
						>
							<el-option
								v-for="item in majorOptions"
								:key="item.majorCode"
								:label="`${item.educateTypeDesc}/${item.subjectCategoryName}/${item.major1Name}/${item.majorName}(${item.majorCode})`"
								:value="item.majorCode"
							/>
						</el-select>
						<el-button
							@click="changeSelect"
							type="primary"
							color="#ff7214"
							style="color: #fff; margin-left: 10px"
							size="large"
							>{{ text }}</el-button
						>
					</div>
				</div>
				<div class="profession">
					<div class="title">
						<div class="one">2</div>
						<div class="two">/5</div>
						<div class="tip">预估分数</div>
					</div>
					<el-input v-model="score" size="large" placeholder="请输入0-500区间的整数" @change="scoreChange">
						<template #append>
							<div>分</div>
						</template>
					</el-input>
				</div>
				<div class="profession">
					<div class="title">
						<div class="one">3</div>
						<div class="two">/5</div>
						<div class="tip">目标院校层次</div>
					</div>
					<el-select v-model="tag" clearable size="large" class="search" @change="schoolLevelChange" placeholder="学校层次">
						<el-option v-for="item in schoolType" :key="item" :label="item" :value="item"/>
					</el-select>
				</div>
<!--				<div class="profession">-->
<!--					<div class="title">-->
<!--						<div class="one">4</div>-->
<!--						<div class="two">/7</div>-->
<!--						<div class="tip">数学偏好</div>-->
<!--					</div>-->
<!--					<el-select v-model="mathKeyWords" clearable size="large" class="search" @change="mathChange" placeholder="数学偏好">-->
<!--						<el-option v-for="item in mathOption" :key="item" :label="item" :value="item"/>-->
<!--					</el-select>-->
<!--				</div>-->
<!--				<div class="profession">-->
<!--					<div class="title">-->
<!--						<div class="one">5</div>-->
<!--						<div class="two">/7</div>-->
<!--						<div class="tip">外语偏好</div>-->
<!--					</div>-->
<!--					<el-select v-model="englishKeyWords" clearable size="large" class="search" @change="englishChange" placeholder="外语偏好">-->
<!--						<el-option v-for="item in englishOption" :key="item" :label="item" :value="item"/>-->
<!--					</el-select>-->
<!--				</div>-->
				<div class="profession">
					<div class="title">
						<div class="one">4</div>
						<div class="two">/5</div>
						<div class="tip">学习方式</div>
					</div>
					<el-select v-model="applyLearningStyle" clearable size="large" class="search" @change="learningChange" placeholder="学习方式">
						<el-option v-for="item in studyType" :key="item.value" :label="item.name" :value="item.value"/>
					</el-select>
				</div>
				<div class="profession">
					<div class="title">
						<div class="one">5</div>
						<div class="two">/5</div>
						<div class="tip">专项计划</div>
					</div>
					<el-select v-model="planType" clearable size="large" class="search" @change="planChange" placeholder="专项计划">
						<el-option v-for="item in planTypeOption" :key="item" :label="item" :value="item"/>
					</el-select>
				</div>
				
			</div>
			<div class="result">
				<el-button type="primary" color="#ff7214" size="large" @click="getSearchResult">AI 择校</el-button>
			</div>
		</template>
    <!-- overflow: auto; -->
    <div style="padding: 0 calc((100vw - 1200px)/2);height: 100%;" v-else>
      <div class="change" style="display: flex;align-items: center;justify-content: space-between">
        <el-button  :icon="ArrowLeft" type="primary" color="#ff7214" @click="searchRest" style="color: #fff;" size="large">重新生成</el-button>
        <el-button type="primary" @click="showExport" size="large" color="#ff7214" style="color: #fff">导出报告</el-button>
      </div>
      <div class="filter">
        <div class="item">
          <div class="left">
            <div class="title">院校位置</div>
            <img class="arrow" src="../../assets/images/arrow_right.png" />
          </div>
          <div class="center" :class="{ active: selectArea === '全部' }" style="font-size: 14px; cursor: pointer" @click="clickItem({ name: '全部' })">全部</div>
          <div class="pro-right">
            <div class="a-con">
              <div class="a-left">A区</div>
              <div class="a-right">
                <div class="ele" v-for="ele in provinceData.azone" :key="ele.code" :class="{ active: ele.name === selectArea }" @click="clickItem(ele)">{{ ele.name }}</div>
              </div>
            </div>
            <div class="a-con">
              <div class="a-left">B区</div>
              <div class="a-right">
                <div
                  class="ele"
                  :class="{ active: ele.name === selectArea }"
                  v-for="ele in provinceData.bzone"
                  :key="ele.code"
                  @click="clickItem(ele)"
                >
                  {{ ele.name }}
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="item">
          <div class="left">
            <div class="title">学校层次</div>
            <img class="arrow" src="../../assets/images/arrow_right.png" />
          </div>
          <div class="right">
            <div
              class="ele"
              v-for="ele in schoolType"
              :key="ele"
              :class="{ active: ele === tag }"
              @click="clickTag(ele)"
            >
              {{ ele }}
            </div>
          </div>
        </div>
        <div class="item">
          <div class="left">
            <div class="title">学习方式</div>
            <img class="arrow" src="../../assets/images/arrow_right.png" />
          </div>
          <div class="right">
            <div
              class="ele"
              v-for="ele in studyType"
              :key="ele"
              :class="{ active: ele.value === applyLearningStyle }"
              @click="clickStudyType(ele)"
            >
              {{ ele.name }}
            </div>
          </div>
        </div>
        <div class="item">
          <div class="left">
            <div class="title" style="display: flex;align-items: center">
              <span>院校梯度</span>
              <el-popover placement="right" :width="520" trigger="hover">
                <template #reference>
                  <el-icon color="#8a8a8a"><QuestionFilled /></el-icon>
                </template>
                <div class="cons" style="color: #333">
                  <div><span style="font-weight: 500">可冲刺：</span>难度较大，蹦起来才上岸的目标院校，成功率在50%左右</div>
                  <div><span style="font-weight: 500">较稳妥：</span>难度适中，跳一跳能够上岸的目标院校，成功率在70%以上</div>
                  <div><span style="font-weight: 500">可保底：</span>难度一般，只要不放弃学习能够上岸的目标院校，成功率在80%以上</div>
                </div>
              </el-popover>
            </div>
            <img class="arrow" src="../../assets/images/arrow_right.png" />
          </div>
          <div class="right">
            <div
              class="ele"
              v-for="ele in schoolGradientOptions"
              :key="ele.value"
              :class="{ active: ele.value === recommendType }"
              @click="clickRecommendType(ele)"
            >
              {{ ele.label }}
            </div>
          </div>
        </div>
      </div>
      <div
        class="list"
        v-loading="searchLoading"
        element-loading-text="数据加载中..."
      >
        <ListItem v-if="!searchLoading" :data="aiList"></ListItem>
      </div>
      <Pagination
        v-if="aiList.length> 0"
        :total="total"
        :pageNum="pageNum"
        :pageSize="pageSize"
        @currentChange="pageChange"
        @sizeChange="sizeChange"
      ></Pagination>
    </div>
    <el-dialog
      v-model="downDialog"
      title="导出报告"
      width="30%"
      :before-close="handleClose"
    >
			<div class="down-tips">导出时间约为5分钟,可到邮箱查看</div>
      <el-input v-model="email" placeholder="请输入邮箱地址" @change="emailChange"></el-input>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" color="#ff7214" style="color:#fff" @click="exportExcel">下载</el-button>
      </span>
      </template>
    </el-dialog>
		<!-- 展示公众号图片 -->
		<el-dialog
			v-model="dialogUrlShow"
      width="440px"
		>
			<div style="width: 400px;text-align: center">
				<img style="width: 400px;" :src="dialogUrl.imageUrl"/>
        <p v-for="ele in dialogUrl.tips" :key="ele" style="text-align: left;font-size: 14px;color: #333">{{ele}}</p>
			</div>
		</el-dialog>
  </div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { decrypt } from '@/utils/parseDate'
import ListItem from '@/components/listItem/ListItem.vue'
import Pagination from '@/components/pagination/Pagination'
import { ElMessage } from 'element-plus'
import {QuestionFilled} from '@element-plus/icons-vue'
import {ArrowLeft} from '@element-plus/icons-vue'
import {useStore} from 'vuex'
// 获取store
const store = useStore()
import {
  professionList,
  schoolLevel,
  province,
  train,
  second,
  aiResult,
  searchMajorData,
  english,
  planListData,
  downloadReport,
  aiReportLimit,
  specialPlan,
  popupStatus
} from '@/api/api'
// 是否搜索
const unSearch = ref(false)
// 搜索专业
const search = ref('')
const majorOptions = ref([])
const searchMajorLoading = ref(false)
const searchLoading = ref(false)
const options = ref([])
const score = ref('')
const provinceData = ref({})
const studyType = ref([
  {
    name: '全日制',
    value: 1
  },
	{
		name: '非全日制',
		value: 0
	}
])
// 院校梯度
const recommendType = ref(0)
const schoolGradientOptions = ref([
  {
    label: '全部',
    value: 0
  },
  {
    label: '可冲刺',
    value: 1
  },
  {
    label: '较稳妥',
    value: 2
  },
  {
    label: '可保底',
    value: 3
  }
])
const dialogUrl = ref('')
const dialogUrlShow = ref(false)
// 数学偏好
const mathKeyWords = ref('')
const mathOption = ref(['数学一','数学二','数学三','不考数学'])
// 英语类型
const englishKeyWords = ref('')
const englishOption = ref([])
// 专项计划
const planType = ref('')
const planTypeOption = ref([])
// 学习方式
const applyLearningStyle = ref('')
// 培养类型:学硕 专硕
const educateTypeOption = ref([
  {
    label: '学术型硕士',
    value: 1
  },
  {
    label: '专业学位硕士',
    value: 2
  }
])
// 省份code
const provinceCodes = ref('')
// 搜索类型
const selectType = ref(true)
const text = ref('切换模糊输入')
const selectTag = ref('') // 搜索标签
const selectStudyType = ref('') // 学习方式筛选
// 下载输入邮箱弹窗
const email = ref('')
const downDialog = ref(false)
// 点击院校梯度
function clickRecommendType(val){
  recommendType.value = val.value
  getSearchResult()
}
// 获取计划类型
async function getSpecialPlan(){
  try{
    const data = await specialPlan()
    if(data.status === 0){
      planTypeOption.value = JSON.parse(data.result)
    }
  }catch (e) {}
}
// 切换学习方式
function learningChange(val){
  applyLearningStyle.value = val
}
// 切换数学偏好
function mathChange(val){
  mathKeyWords.value = val
}
// 切换英语偏好
function englishChange(val){
  englishKeyWords.value = val
}
// 切换专项计划
function planChange(val){
  planType.value = val
}
// 展示下载邮箱
async function showExport(){
  try{
    const result = await popupStatus()
    if(result.result === 'false'){
      getAiReportLimit()
    } else {
      downDialog.value = true
      email.value = ''
    }
  }catch (e) {
  
  }
  
}
// 关闭下载弹窗
function handleClose(){
  downDialog.value = false
}
// 校验邮箱
function emailChange(val){
  const reg = /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/
  if(!reg.test(val)){
    ElMessage.error('请输入正确的邮箱地址!')
    return
  }
  email.value = val
}
function changeSelect() {
  if (selectType.value) {
    text.value = '切换精确输入'
  } else {
    text.value = '切换模糊输入'
  }
  selectType.value = !selectType.value
}
// 重新搜索
function searchRest(){
  selectArea.value = '全部'
  recommendType.value = 0
  provinceCodes.value = ''
  tag.value = ''
  applyLearningStyle.value = ''
  unSearch.value = false
}
// 分页
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
// 页码改变
function pageChange(page){
  pageNum.value = page
  getSearchResult()
}
// 分页大小改变
function sizeChange(size){
  pageNum.value = 1
  pageSize.value = size
  getSearchResult()
}
// 输入搜索专业
function selectMajor(val) {
}
// 远程获取专业
async function remoteMethod(val){
	try {
		if(!val)return
		const data = {
			majorNameKeyWords: val
		}
		searchMajorLoading.value = true
		const result = await searchMajorData(data)
		if(result.status === 0){
			majorOptions.value = result.result
			searchMajorLoading.value = false
		}
	} catch (error) {
		searchMajorLoading.value = false
	}
}
const props = {
  lazy: true,
  children: 'children',
  lazyLoad: (node, resolve) => {
    const { level, pathValues } = node
    if (level === 1) {
      train().then(res => {
        if (res.status === 0) {
					let arr = []
					if(pathValues[0]==1){
						arr = res.result.subjectCategoryRsps.map(ele => ({
							label: ele.subjectCategoryName,
							leaf: level >= 3,
							value: ele.subjectCategoryCode
						}))
					} else if(pathValues[0]==2){
						arr = res.result.subjectCategoryRspsForZhuan.map(ele => ({
							label: ele.subjectCategoryName,
							leaf: level >= 3,
							value: ele.subjectCategoryCode
						}))
					}
          resolve(arr)
        } else {
          resolve(undefined)
        }
      })
    }
    if (level === 2) {
      second({
        subjectCategoryCode: pathValues[1],
        educateType: pathValues[0]
      }).then(res => {
        if (res.status === 0) {
          const arr = res.result.map(ele => ({
            label: ele.major1Name,
            leaf: level >= 3,
            value: ele.major1Code
          }))
          if (arr.length === 0) {
            resolve(undefined)
          } else {
            resolve(arr)
          }
        } else {
          resolve(undefined)
        }
      })
    }
    if (level === 3) {
      professionList({
        educateTypes: pathValues[0],
        subjectCategoryCode: pathValues[1],
        major1Code: pathValues[2]
      }).then(res => {
        if (res.status === 0) {
          const arr = res.result.data.map(ele => ({
            label: ele.majorName,
            value: ele.majorCode,
            leaf: level >= 3
          }))
          resolve(arr)
        } else {
          resolve(undefined)
        }
      })
    }
    if (level === 4) {
      resolve(undefined)
    }
  }
}
// 学校层次
const tag = ref('')
const schoolType = ref([])
// 院校地区
const selectArea = ref('全部')
// ai择校结果
const aiList = ref([])
// 搜索专业
async function searchProfession(search) {
  try {
    // if (!search) {
    //   ElMessage.warning("请输入专业名称!");
    // }
  } catch (error) {
    // throw new Error(error)
  }
}
// 分数变化
function scoreChange(val) {
  const value = parseInt(val)
  if (!isNaN(value)) {
    if (val > 500) {
      ElMessage.warning('分数不能大于500分!')
    } else if (val < 0) {
      ElMessage.warning('分数不能小于0分!')
    } else {
      score.value = val
    }
  } else {
    ElMessage.warning('请输入正整数!')
    score.value = ''
  }
}
// ai择校
async function getSearchResult() {
  try {
    if (!search.value) {
      ElMessage.warning('请输入专业名称!')
      return
    }
    if (!score.value) {
      ElMessage.warning('请输入你的分数!')
      return
    }
		let majorCode = ''
		if(typeof search.value === 'string'){
			majorCode = search.value
		} else {
			majorCode = search.value[search.value.length - 1]
		}
    const data = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      estimateScore: score.value,
      majorCode: majorCode,
      tag: tag.value,
      provinceCodes: provinceCodes.value,
      mathKeyWords: mathKeyWords.value,
      englishKeyWords: englishKeyWords.value,
      soldierKeyWords: planType.value,
			applyLearningStyle: applyLearningStyle.value,
      recommendType: recommendType.value ? recommendType.value : ''
    }
    unSearch.value = true
    searchLoading.value = true
    const result = await aiResult(data)
    const res = JSON.parse(decrypt(result))
    if (res.status == 8) {
      store.commit("setTipsDialog", true);
    }
    if (res.status == 9) {
      store.commit("setNumberDialog", true);
    }
    if (res.status === 0) {
			if(res.result && res.result.data.length>0){
				res.result.data.forEach(ele => {
					ele.schoolTag = ele.schoolTag.split('|')
					ele.checked = false
				})
        total.value = res.result.total
				aiList.value = res.result.data || []
				searchLoading.value = false
			} else {
				aiList.value = []
				searchLoading.value = false
			}
    } else {
      searchLoading.value = false
    }
  } catch (error) {
		searchLoading.value = false
    // throw new Error(error)
  }
}
// 点击选项
function clickItem(val) {
	if(!(selectArea.value === val.name)){
		selectArea.value = val.name
		provinceCodes.value = val.code
		getSearchResult()
	}
}
// 点击学校类型标签
function clickTag(val) {
	if(!(selectTag.value ===val)){
		selectTag.value = val
		tag.value = val
		getSearchResult()
	}
}
// 筛选学习方式
function clickStudyType(val) {
	if(applyLearningStyle.value !== val.value){
    applyLearningStyle.value = val.value
  	getSearchResult()
	}
}
// 导出报告
async function exportExcel(){
  try{
    let majorCode = ''
    if(typeof search.value === 'string'){
      majorCode = search.value
    } else {
      majorCode = search.value[search.value.length - 1]
    }
    const data = {
      estimateScore: score.value,
      majorCode: majorCode,
      tag: tag.value,
      email: email.value,
      provinceCodes: [provinceCodes.value],
      mathKeyWords: mathKeyWords.value,
      englishKeyWords: englishKeyWords.value,
      soldierKeyWords: planType.value,
      applyLearningStyle: applyLearningStyle.value
    }
    const res = await downloadReport(data)
    const result = JSON.parse(decrypt(res))
    if(result.status === 0){
      ElMessage.success('导出中,请稍后到邮箱查看!')
      downDialog.value = false
      email.value = ''
			// getAiReportLimit()
    } else if(result.status == 88){
			getAiReportLimit()
		}
  }catch (e) {
  }
}
// 导出限制图片
async function getAiReportLimit(){
	try {
		const data = await aiReportLimit()
    const res = JSON.parse(data.result)
    res.tips = res.tips.split('\n')
		if(data.status === 0){
			dialogUrlShow.value = true
			dialogUrl.value = res
		}
	} catch (error) {
	
	}
}
// 输入专业名称搜索
function filterData(val) {
}
// 切换学校层次
function schoolLevelChange(val) {
  tag.value = val
}
// 获取学校层次options
async function getSchoolLevel() {
  try {
    const result = await schoolLevel()
    if (result.status === 0) {
      schoolType.value = JSON.parse(result.result)
    }
  } catch (error) {
    // throw new Error(error)
  }
}
// 获取考研省份
async function getProvince() {
  try {
    const result = await province()
    if (result.status === 0) {
      provinceData.value = result.result
    }
  } catch (error) {
    // throw new Error(error)
  }
}
// 获取培养方式和学科门类
async function getTrain() {
  try {
    const result = await train()
    if (result.status === 0) {
      options.value = result.result.subjectCategoryRsps
    }
  } catch (error) {
    // throw new Error(error)
  }
}
// 选择目标专业
function professionChange(val) {
}
// 获取英语类型
async function getEnglish(){
  try{
    const data = await english()
    if(data.status === 0){
      englishOption.value = JSON.parse(data.result)
    }
  }catch (e) {
  
  }
}
onMounted(() => {
  getSchoolLevel()
  getProvince()
  getTrain()
  getEnglish()
  getSpecialPlan()
  // getAiReportLimit()
})
</script>
<style scoped lang="less">
.ai {
  box-sizing: border-box;
  padding-top: 16px;
  height: 100%;
	width: 100%;
  .loading {
    height: calc(100% - 75px);
    display: flex;
    align-items: center;
    justify-content: center;
    color: #666;
  }
  .unsearch {
		position: relative;
    padding: 24px calc((100vw - 1200px)/2) 0;
		min-width: 1200px;
    font-family: PingFang SC-Semibold, PingFang SC !important;
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    .profession {
      width: 50%;
      margin-bottom: 16px;
      .title {
        margin-bottom: 16px;
        display: flex;
        align-items: baseline;
        .one {
          color: #ff7214;
          font-style: normal;
          font-size: 24px;
          font-weight: 600;
        }
        .two {
          letter-spacing: 5px;
          font-size: 16px;
          font-weight: 600;
          color: rgba(0, 0, 0, 0.4);
          margin-right: 10px;
          margin-left: 6px;
        }
        .tip {
          font-size: 20px;
          font-weight: 500;
          color: #000;
        }
      }
      .search {
        width: 400px;
      }
      /deep/ .el-input {
        width: 400px;
        text-align: left;
      }
    }
  }
	.result {
		box-sizing: border-box;
		padding: 24px calc((100vw - 1200px)/2) 0;
		min-width: 1200px;
		width: 100%;
		text-align: center;
      .el-button {
				width: 360px;
        color: #fff;
      }
    }
  .list {
		box-sizing: border-box;
    margin-top: 20px;
    padding: 0px 20px;
    border: 1px solid rgb(238, 238, 238);
    overflow: hidden;
    min-height: 280px;
		min-width: 1200px;
  }
  .filter {
    box-sizing: border-box;
    height: 255px;
    margin-top: 12px;
    padding: 20px 20px 10px;
		min-width: 1200px;
    // padding: 24px calc((100vw - 1080px)/2) 0;
    border: 1px solid rgb(238, 238, 238);
    .item {
      margin-bottom: 12px;
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: start;
      .active {
        color: #ff7214;
      }
      .left {
        display: flex;
        align-items: center;
        width: 110px;
        .el-icon{
          margin-left: 6px;
        }
        .arrow {
          margin-top: -1px;
          margin-left: 12px;
          width: 12px;
          height: 12px;
        }
      }
      .right {
        flex: 1;
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        .ele {
          margin-bottom: 12px;
          padding: 0 12px;
          font-size: 14px;
          cursor: pointer;
        }
        .ele:hover {
          color: #ff7214;
          cursor: pointer;
        }
      }
      .pro-right {
        margin-left: 24px;
        display: block;
        flex: 1;
        font-size: 14px;
        .a-con {
          margin-bottom: 12px;
          display: flex;
          //align-items: center;
          .a-left {
            width: 40px;
            color: #666;
          }
          .a-right {
            flex: 1;
            display: flex;
            flex-wrap: wrap;
            align-items: flex-start;
            .ele {
              margin-bottom: 12px;
              padding: 0 12px;
              font-size: 14px;
              cursor: pointer;
            }
            .ele:hover {
              color: #ff7214;
              cursor: pointer;
            }
          }
        }
      }
    }
  }
}
.down-tips{
	margin-bottom: 12px;
	color: #f56c6c;
}
</style>
